#include "addcollegewindow.h"
#include "ui_addcollegewindow.h"
#include <QMessageBox>
#include <QFile>
#include <QTextStream>

AddCollegeWindow::AddCollegeWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AddCollegeWindow)
{
    ui->setupUi(this);
}

AddCollegeWindow::~AddCollegeWindow()
{
    delete ui;
}

void AddCollegeWindow::on_addButton_clicked()
{
    QString name = ui->nameLineEdit->text();
    if (name.isEmpty()) {
        QMessageBox::warning(this, "警告", "学院名称不能为空");
        return;
    }

    // 检查是否有重复数据
    QFile file("data.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::warning(this, "错误", "无法打开文件进行读取");
        return;
    }

    QTextStream in(&file);
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(" ");
        if (fields[0] == "C" && fields[2] == name) {
            QMessageBox::warning(this, "警告", "学院名称已存在");
            file.close();
            return;
        }
    }
    file.close();

    emit collegeAdded(name);
    QMessageBox::information(this, "提示", "学院添加成功");
    this->close();
}
